<template>
  <div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="{ type: 'checkbox', columnWidth: 30, selectedRowKeys: checkedKeys, onChange: onSelectChange, }">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleAdd">新增</a-button>
        <a-button type="primary" @click="openHistoryDialog">从历史工分库移入</a-button>
        <a-button type="primary" @click="openTypicalDialog" disabled>从典型工分库移入</a-button>
        <!-- <a-button type="primary" preIcon="ant-design:export-outlined" @click="onExportXls">导出</a-button>
        <j-upload-button type="primary" preIcon="ant-design:import-outlined" @click="onExportXls">导入</j-upload-button> -->
        <a-dropdown v-if="checkedKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined" />
                删除
              </a-menu-item>
            </a-menu>
          </template>
          <a-button>批量操作
            <Icon icon="mdi:chevron-down" />
          </a-button>
        </a-dropdown>

      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" />
      </template>
    </BasicTable>
    <!-- 表单区域 -->
    <HubTeamIndexModal @register="registerModal" @success="handleSuccess" />
    <!-- 历史库 -->
    <HistoryDialog @register="registerHistoryModal" @success="handleSuccess" :columns="columns" :treeDataBase="treeDataBase" :pageList="list" treeTitle="workTypeName" treeValue="workTypeCode" :importHistory="importHistory" title="选择工作类型" />
  </div>
</template>

<script lang="ts" name="emp-team-index-HubTeamWork" setup>
import { ref, onMounted, reactive, nextTick, watchEffect, computed, unref, watch, defineComponent } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { useModal } from '/@/components/Modal';
import { useListPage } from '/@/hooks/system/useListPage';
import HubTeamIndexModal from './components/HubTeamWorkModal.vue';
import HistoryDialog from '../historyDialog.vue';
import { columns, searchFormSchema } from './HubTeamWork.data';
import { list, deleteOne, batchDelete, getImportUrl, getExportUrl, updateList, treeList, importHistory, typicalPageList, importModelHistory, } from './HubTeamWork.api';
import { useMessage } from '/@/hooks/web/useMessage';
import dayjs from 'dayjs';
import { useUserStore } from '/@/store/modules/user';
const userStore = useUserStore();
// import { columns: typical } from '../HubTeamWork1/HubTeamWork1.data'
// 轻提醒
const { createMessage: $message } = useMessage();
import { initDictOptions } from '/@/utils/dict/index';

// 树形控件
const selectedKeys = ref([]);
const treeDataBase = ref([]);
// 导入导出的显示与隐藏
const flag = ref<boolean>(false);
const checkedKeys = ref<Array<string | number>>([]);
//注册model
const [registerModal, { openModal }] = useModal();
// 注册历史库model
const [registerHistoryModal, { openModal: openHistoryModal = () => { } }] = useModal();
//注册table数据
const { prefixCls, tableContext, onExportXls, onImportXls, } = useListPage({
  tableProps: {
    title: '指标库',
    api: list,
    columns,
    canResize: false,
    // dataSource: mockDate,
    showIndexColumn: true,
    rowKey: 'id',
    beforeFetch: (params) => {
      return Object.assign(params);
    }, //表格和查询条件同步更新的方法
    formConfig: {
      //labelWidth: 120,
      schemas: searchFormSchema,
      autoSubmitOnEnter: true,
      showAdvancedButton: true,
      fieldMapToNumber: [],
      fieldMapToTime: [],
    },
    actionColumn: {
      width: 120,
      fixed: 'right',
    },
    immediate: true,
  },
  exportConfig: {
    name: '工作积分标准',
    url: getExportUrl,
  },
  importConfig: {
    url: getImportUrl,
    success: handleSuccess,
  },
});

const [registerTable, { getForm, reload, setTableData }] = tableContext;

const teamList = userStore.getTeamList;
const orgName = ref('');

/* componentProps: {
      api: initDictOptions,
      params: 'hub_work_item_count',
      fieldNames: {
        label: 'text',
        value: 'value',
      },
    }, */

// 默认执行一次
onMounted(async () => {
  let form = getForm();
  let selectdata = await initDictOptions('hub_work_item_count');
  selectdata.forEach((r) => {
      r['label'] = r.text;
      r['value'] = r.value;
    });
  form.updateSchema([
    {
      field: 'orgCode',
      componentProps: {
        onChange: (e) => {
          // setTableData([]);
          reload();
        },
        // atfer request callback
        onOptionsChange: (options) => {
          console.log('get options', options.length, options);
        },
      },
    },
  ]);
});

let childNodes = [];
/**
 * 判断类型是否为子节点
 */
function isChildNode(nodeArr) {
  nodeArr.forEach((item) => {
    if (item.children) {
      isChildNode(item.children);
    } else {
      childNodes.push(item);
    }
  });
}
/**
 * 新增事件
 */
function handleAdd() {
  let params = checkPeriodAndOrgExist();
  if (params) {
    childNodes = [];
    isChildNode(treeDataBase.value);
    openModal(true, {
      isUpdate: false,
      showFooter: true,
      record: {
        ...params
      },
    });
  }
}

function checkPeriodAndOrgExist() {
  let params = getForm().getFieldsValue();
  let orgCode = params.orgCode;
  let periodCode = params.periodCode;
  if (!periodCode) {
    $message.error('请先选择考核周期！');
    return;
  }
  if (!orgCode) {
    $message.error('请先选择班组！');
    return;
  }
  const option = teamList.filter((item) => item.value === orgCode);
  orgName.value = option[0].label;
  let resParams = {
    periodCode: periodCode,
    orgCode: orgCode,
    orgName: orgName.value,
  }
  return resParams;
}

/**
 * 编辑事件
 */
function handleEdit(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
    showFooter: true,
  });
}
/**
 * 详情
 */
function handleDetail(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
    showFooter: false,
  });
}
/**
 * 删除事件
 */
async function handleDelete(record) {
  await deleteOne({ id: record.id }, handleSuccess);
}
/**
 * 批量删除事件
 */
async function batchHandleDelete() {
  await batchDelete({ ids: checkedKeys.value }, handleSuccess);
}
/**
 * 成功回调
 */
function handleSuccess() {
  reload();
}
/**
 * 操作栏
 */
function getTableAction(record) {
  return [
    {
      label: '编辑',
      onClick: handleEdit.bind(null, record),
    },
    {
      label: '删除',
      popConfirm: {
        title: '是否确认删除',
        confirm: handleDelete.bind(null, record),
      },
    },
  ];
}

// 获取批量删除参数
function onSelectChange(selectedRowKeys: (string | number)[]) {
  checkedKeys.value = selectedRowKeys;
}

const handleSuccessByHistory = () => {
  console.log('打开历史弹窗成功');
};

function openHistoryDialog() {
  let params = checkPeriodAndOrgExist();
  if (params) {
    //弹出框左侧树数据
    treeList({ orgCode: params.orgCode }).then((res) => {
      treeDataBase.value = res;
    });
    openHistoryModal(true, {
      ...params,
      showFooter: false,
    });
  }
};

const handleSuccessByTypical = () => {
  console.log('打开典型库弹窗成功');
};

const openTypicalDialog = () => {
  $message.info('典型工分库导入');
};
</script>

<style scoped lang="less">
/deep/.ant-table-wrapper {
  padding: 16px !important;
}

.treeBox {
  margin-right: 10px;
  background-color: white;
  height: calc(100% - 20px);
  width: 270px;
}

.table-width {
  width: calc(100% - 350px);
}

.treeTitle {
  margin-top: 10px;
  background-color: #009688;
  width: 100%;
  height: 40px;
  line-height: 40px;
  text-align: center;
  color: #fff;
  font-size: 20px;
}
</style>
